/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DataAccess;

import Entity.IDoc;
import Servlet.PMF;
import java.util.Date;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author phuc
 */
public class IDocAccess {
    PersistenceManager pm;
    public IDocAccess()
    {
        pm = PMF.get().getPersistenceManager();
    }
    public IDoc getIDocByID(Long IDocID)
    {
        IDoc idoc = new IDoc();

        Query q = pm.newQuery(IDoc.class,"IDocID == id");
        q.declareParameters("Long id");
        List<IDoc> results = (List<IDoc>)q.execute(IDocID);
        idoc = results.get(0);
        if (results.size() > 0)
        {
            return idoc;
        }
        return null;
    }
    public Boolean addIDoc(IDoc idoc)
    {
        try{
            pm.makePersistent(idoc);
            return true;
        }
        catch(Exception e){
            return false;
        }
        finally
        {
            pm.close();
        }        
    }
    public List<IDoc> searchIDoc(String PubNum, String Subject, Date FromDate, Date ToDate)
    {
        
        Query q = pm.newQuery(IDoc.class);
        List<IDoc> results = null;
        if (!PubNum.trim().equals(("")))
        {
            q.setFilter("PubNum == pubnum && Subject == sub && DraftDate >= FromDate && DraftDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("String pubnum, String sub,Date FromDate, Date ToDate");
            results = (List<IDoc>)q.executeWithArray(PubNum,Subject,FromDate,ToDate);
        }
        else if (!Subject.equals(""))
        {
            q.setFilter("Subject == sub && DraftDate >= FromDate && DraftDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("String sub,Date FromDate, Date ToDate");
            results = (List<IDoc>)q.executeWithArray(Subject,FromDate,ToDate);
        }
        else if (FromDate != null && ToDate != null)
        {
            q.setFilter("DraftDate >= FromDate && DraftDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("Date FromDate, Date ToDate");
            results = (List<IDoc>)q.executeWithArray(FromDate,ToDate);
        }
        else
            results = (List<IDoc>)q.execute();

        if (results.size() > 0)
            return results;
        return null;
    }
    public void deleteIDocByID(Long ID){
        IDoc idoc = getIDocByID(ID);
        pm.deletePersistent(idoc);
    }
    
}
